<?php
/**
 * Fonction de purge des parties terminées
 * Supprime toutes les parties antérieures à $delai heures
 */
$delai = (int)validGET('delai');
$force = (bool)validGET('force');

$delaiSeconde = $delai * 60 * 60;
$dateSuppression = date(DATE_ATOMZ, time() - $delaiSeconde);

echo 'Purge de toutes parties anterieures a ' . $dateSuppression . ' heures. </br></br>';
if($force){
	echo 'Meme les non terminees.</br></br>';
}
$deletedGames = array();
$aliveGames = array();
$instanceGames = array();

$gameIds = getGameIds();

foreach($gameIds as $gameId){
	$game = loadGame($gameId);
	if($force || $game['endOfGame'] != 0){
		if($game['update_date'] < $dateSuppression){
			$deletedGames[] = array('gameId' => $gameId, 'updateDate' => $game['update_date'], 'author' => $game['author'], 'players' => array_keys($game['players']));
			releasePlayerCards(loadGame($gameId));
			unlink(DIR_GAME . $gameId);
		}else{
			$instanceGames[] = array('gameId' => $gameId, 'updateDate' => $game['update_date'], 'author' => $game['author'], 'players' => array_keys($game['players']));
		}
	}else{
		$aliveGames[] = array('gameId' => $gameId, 'updateDate' => $game['update_date'], 'author' => $game['author'], 'players' => array_keys($game['players']));
	}
}
   
    
echo('Parties purgees :</br>');
echoGameLines($deletedGames);
echo '</br>';

echo('Parties toujours en cours :</br>');
echoGameLines($aliveGames);
echo '</br>';

echo('Parties en instance de purge :</br>');
echoGameLines($instanceGames);
    
    
   
function echoGameLines($games){
    if(count($games) > 0){
	    foreach($games as $gameTmp){
	    	$joueursStr = array();
	    	foreach($gameTmp['players'] as $playerId ){
	    		if($playerId != 'CPU'){
	    			$joueursStr[] = sprintf('<a href="%s/admin/view/player/%s">%s</a>', PATH_ROOT, $playerId, $playerId);
	    		}
	    	}
	    	echo(sprintf('<a href="%s/admin/view/game/%s">%s</a> - Mise a jour : %s - Auteur : <a href="%s/admin/view/player/%s">%s</a> - Joueurs : %s.</br>'
	    	     , PATH_ROOT, $gameTmp['gameId'], $gameTmp['gameId']
	    	     , $gameTmp['updateDate']
	    	     , PATH_ROOT, $gameTmp['author']
	    	     , $gameTmp['author']
	    	     , implode('-', $joueursStr)
	    	     ));
	    }    
    }else{
    	echo('Aucune.</br>');	
    }	
	return ;
}

